package org.zjt.chapter1.io;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.util.internal.SystemPropertyUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.Locale;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-07-12 下午9:15
 * @see
 */
@Slf4j
public class EpollNetworkOperationalTest {
    @Test
    public void server()  {
        EpollEventLoopGroup eventExecutors = new EpollEventLoopGroup();
        try {
            ChannelFuture sync = new ServerBootstrap().group(eventExecutors).channel(EpollServerSocketChannel.class).childHandler(new SimpleChannelInboundHandler<Object>() {
                @Override
                protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
                    log.info("msg:{}", o);  // SimpleChannelInboundHandler 自动释放poolByteBuf内存
                }
            }).bind(5004).sync();
            sync.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            eventExecutors.shutdownGracefully();
        }
    }

    @Test
    public void client()  {
        EpollEventLoopGroup eventExecutors = new EpollEventLoopGroup();
        try {
            ChannelFuture localhost = new Bootstrap().group(eventExecutors).channel(EpollSocketChannel.class).handler(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    ctx.writeAndFlush(Unpooled.directBuffer().writeBytes("zhangssds".getBytes()));
                }
            }).connect("localhost", 5004).sync();

            localhost.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            eventExecutors.shutdownGracefully();
        }
    }


    public Boolean supportEpoll() {
        String name = SystemPropertyUtil.get("os.name").toLowerCase(Locale.UK).trim();
        return name.startsWith("linux") ? Boolean.TRUE : Boolean.FALSE;
    }
}
